# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv

import os
import sys
import jinja2

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_ext', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class product_template(osv.osv):
    _inherit = 'product.template'

    def _get_editor_html(self, cr, uid, ids, field_name, arg, context=None):
        template = env.get_template('editor.html')
        res = {}
        for product in self.browse(cr, uid, ids, context=context):
            res[product.id] = template.render({'editor_id': product.id, 'shop_id': 0})

        return res

    _columns = {
        'description_editor': fields.function(_get_editor_html, type='html', string=u'描述编辑器'),
        'description_editor_ids': fields.one2many('description.editor.row', 'product_id', u'描述记录'),
    }


class description_editor_row(osv.Model):
    _name = 'description.editor.row'

    _order = 'index asc'

    _columns = {
        'product_id': fields.many2one('product.template', u'产品'),
        'index': fields.integer(u'序号'),
        'value': fields.text(u'实际值'),
        'component': fields.char(u'组件'),
    }

    def unlink(self, cr, uid, ids, context=None):
        for row in self.browse(cr, uid, ids, context=context):
            if row.component == 'image-input':
                filename = row.value.lstrip('editor_image?filename=')
                if os.path.isfile(filename):
                    os.remove(filename)

        return super(description_editor_row, self).unlink(cr, uid, ids, context=context)
